package cn.edu.scau.cmi.front.controller;

/*pengyujin*/

import java.io.BufferedInputStream;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.domain.Detectmethod;
import cn.edu.scau.cmi.ema.domain.Detectstandard;
import cn.edu.scau.cmi.ema.domain.Feature;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;

@Controller("FrontFoodDetectController")
public class FrontFoodDetectController extends FrontCmiEmaController {

	@RequestMapping("/frontDetectMethods")
	public ModelAndView frontDetectMethods(@ModelAttribute CmiPagination page) {

		ModelAndView mav = new ModelAndView();


		Set<String> basicAttributes = null;//detectmethodPaginationService.getDetectmethodBasicAttributes();
		Set<Detectmethod> detectmethods = null;//detectmethodPaginationService.getDetectmethodRecords(page);

		mav.addObject("basicAttributes", basicAttributes);

		mav.addObject("basicAttributesSize", basicAttributes.size());

		mav.addObject("detectmethods", detectmethods);

		mav.addObject("page", page);

		mav.addObject("entityName", "Detectmethod");

		mav.setViewName("front/frontDetectMethods.jsp");

		return mav;
	}

	@RequestMapping("/frontDetectMethodDetail")
	public ModelAndView frontDetectMethodDetail(@RequestParam Integer detectmethodId) {
		ModelAndView mav = new ModelAndView();

		List<Detectstandard> standardList = new ArrayList<Detectstandard>();
		Set<Feature> featureSet = featureDAO.findFeaturesByDetectmethod(detectmethodId, 0, 10);
		for (Feature feature : featureSet) {
			for (Detectstandard detectstandard : feature.getDetectstandardsForFeature()) {
				standardList.add(detectstandard);
			}
			;
		}
		mav.addObject("detectmethod", detectmethodDAO.findDetectmethodByPrimaryKey(detectmethodId));
		mav.addObject("standardList", standardList);
		mav.setViewName("front/frontDetectMethodDetail.jsp");

		return mav;
	}

	//	知识库：检测标准。
	@RequestMapping("/frontDetectStandards")
	public ModelAndView frontDetectStandards(@ModelAttribute CmiPagination page) {

		ModelAndView mav = new ModelAndView();


		Set<String> basicAttributes = null;//detectstandardPaginationService.getDetectstandardBasicAttributes();
		Set<Detectstandard> detectstandards = null;//detectstandardPaginationService.getDetectstandardRecords(page);

		mav.addObject("basicAttributes", basicAttributes);

		mav.addObject("basicAttributesSize", basicAttributes.size());

		mav.addObject("detectstandards", detectstandards);

		mav.addObject("page", page);

		mav.addObject("entityName", "Detectmethod");

		mav.setViewName("front/frontDetectStandards.jsp");

		return mav;
	}

	/**
	 * 
	 * @param multipartFile 批量检测，根据用户选择来显示结果
	 * @return
	 */
	@RequestMapping(value = "/frontUploadExcle", method = RequestMethod.POST)
	public ModelAndView frontUploadExcle(@RequestParam("load-excle") MultipartFile multipartFile,
			HttpServletRequest request) {
		ModelAndView mav = new ModelAndView();

		String[] userCheck = request.getParameterValues("deleteEntitysId");

		List<Detectstandard> standardList = new ArrayList<Detectstandard>();
		List<Detectstandard> resultstandards = new ArrayList<Detectstandard>();
		List<Integer> list = new ArrayList<Integer>();
		List<String> minList = new ArrayList<String>();
		List<String> maxList = new ArrayList<String>();
		List<String> result = new ArrayList<String>();
		String foodName = null;
		String sender = null;
		String qualified = "合格";
		String Unqualified = "不合格";
		
		BufferedInputStream bf = null;
		try {
			bf = new BufferedInputStream(multipartFile.getInputStream());
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		XSSFWorkbook workbook = null;
		try {
			workbook = new XSSFWorkbook(bf);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		XSSFSheet sheet = workbook.getSheetAt(0);

		int firstrow = sheet.getFirstRowNum();
		// 获取最后一行
		int lastrow = sheet.getLastRowNum();
		// 循环行数依次获取列数
		for (int i = firstrow; i < lastrow + 1; i++) {
			// 获取哪一行i
			Row row = sheet.getRow(i);
			if (row != null) {
				// 获取这一行的第一列
				int firstcell = row.getFirstCellNum();
				// 获取这一行的最后一列
				int lastcell = row.getLastCellNum();

				for (int j = firstcell; j < lastcell; j++) {
					// 获取第j列
					Cell cell = row.getCell(j);

					if (cell != null) {
						if (i ==0 ) {
							foodName = cell.toString();
						}
						if (i ==1 ) {
							sender = cell.toString();
						}
						
						if (i > 2) {// 从第四行开始获取数据
							// 解决从表格中读取数字精度问题
							if (j == 1) {
								NumberFormat nf = NumberFormat.getInstance();
								String s = nf.format(cell.getNumericCellValue());
								list.add(Integer.valueOf(s));
							}
							if (j == 2) { //min
								minList.add(cell.toString());
							}
							if (j == 3) { //max
								maxList.add(cell.toString());
							}
						}
					}
				}
			}
		}

		for (Integer integer : list) {
			standardList.add(detectstandardDAO.findDetectstandardById(integer));
		}

		// 用户选择的checkbox的标准和excle表格的做对比，产生结果
		for (String s : userCheck) {

			for (int i = 0; i < standardList.size(); i++) {
			
				if (Integer.parseInt(s) == standardList.get(i).getId()) {
					// 判定是否合格
					resultstandards.add(standardList.get(i));
					BigDecimal minBigDecimal = new BigDecimal(minList.get(i));
					BigDecimal eminBigDecimal = standardList.get(i).getMin();
					BigDecimal maxBigDecimal = new BigDecimal(maxList.get(i));
					BigDecimal emaxBigDecimal = standardList.get(i).getMax();
					int flag = 1;
					if(minBigDecimal.compareTo(eminBigDecimal) == -1) {
						flag = 0;
					}
					if(maxBigDecimal.compareTo(emaxBigDecimal) == 1) {
						flag = 0;
					}
					if(flag ==1) {
						result.add(qualified);
					}else {
						result.add(Unqualified);
					}
					
					
				}
			}
		}
		
		mav.addObject("foodName", foodName);
		mav.addObject("sender", sender);
		mav.addObject("resultstandards", resultstandards);
		mav.addObject("result", result );
		mav.addObject("minList", minList);
		mav.addObject("maxList", maxList);
		mav.setViewName("front/frontDetectResult.jsp");
		return mav;
	}

}